package bingo.mail;

import java.util.Date;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import net.bingosoft.common.ObjectRegistry;
import net.bingosoft.common.config.Config;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;

/**
 * Aug 19, 2008 2:24:22 PM
 * Author:yangdongyu(yangdy@bingosoft.net)
 * ReadMe:发送邮件的服务提供类,能够根据在Spring中配置的以mailSender为beanId的JavaMailSender的实现来发送
 * 		  邮件,也可通过cogfig下面的属性文件指定mailSender的相关属性来构造一个JavaMailSenderImpl来发送邮件
 * 		  eg:我们可以在config包下面创建一个配置文件mail.properties,然后指定以下重要属性:
 * 			mail.host=发送邮件的服务器地址
 * 			mail.username=发送邮件使用邮箱的用户名称
 * 			mail.password=发送邮件使用邮箱的用户密码
 * 			mail.port=smtp发送邮件使用的端口号,该值默认为25
 * 			mail.protocol=邮件的发送协议,默认为smtp
 * 		  
 * ChangeLog:
 */
public class SpringMailSender {
	private static final Log log = LogFactory.getLog(SpringMailSender.class);

	private static JavaMailSender sender ;

	static {
		if(ObjectRegistry.containsBean("mailSender")){
			sender = ObjectRegistry.getBean("mailSender", JavaMailSender.class);
		}else{
			JavaMailSenderImpl javaMailSenderImpl = new JavaMailSenderImpl();

			javaMailSenderImpl.setUsername(Config.getString("mail.username"));
			javaMailSenderImpl.setPassword(Config.getString("mail.password"));
			javaMailSenderImpl.setHost(Config.getString("mail.host"));
			javaMailSenderImpl.setPort(Config.getInt("mail.port", 25));
			javaMailSenderImpl.setProtocol(Config.getString("mail.protocol", "smtp"));
			sender = javaMailSenderImpl;
		}


	}

	private SpringMailSender(){}

	/**
	 * 发带有附件的邮件
	 * @param subject 邮件主题
	 * @param content 邮件内容
	 * @param attachFile 附件(多附件以;号分隔)
	 * @param from 发件人邮箱
	 * @param to 收件人邮箱(多收件人邮箱以;号分隔)
	 */
	public static void sendMail(String subject,String content,String attachFile,String from,String to){


		try{
			MimeMessage mimeMessage = sender.createMimeMessage();
			String[] toUserAddressList = to.split(";");
			//设置收信人
			InternetAddress[] address = new InternetAddress[toUserAddressList.length]; 
			for (int i = 0; i < toUserAddressList.length; i++){ 
				address[i] = new InternetAddress(toUserAddressList[i]); 
			} 
			mimeMessage.setRecipients(Message.RecipientType.TO, address);
			//设置发信人
			mimeMessage.setFrom(new InternetAddress(from));
			//设置主题
			mimeMessage.setSubject(subject, "GBK"); 
			Multipart multipart = new MimeMultipart();
			//向Multipart添加正文
			MimeBodyPart mbpContent = new MimeBodyPart();
			mbpContent.setText(content);
			//向MimeMessage添加（Multipart代表正文）
			multipart.addBodyPart(mbpContent);
			if(attachFile != null && attachFile.trim().length() != 0 ){
				//附件文件集合
				final String[] attachFiles = attachFile.split(";");
				//向Multipart添加附件
				for(int i = 0; i < attachFiles.length; i++){
					MimeBodyPart mimeBodyPart = new MimeBodyPart();
					String filename = attachFiles[i];
					FileDataSource fds = new FileDataSource(filename);
					mimeBodyPart.setDataHandler(new DataHandler(fds));
					mimeBodyPart.setFileName(fds.getName());
					multipart.addBodyPart(mimeBodyPart);
				} 
			}

			//向Multipart添加MimeMessage
			mimeMessage.setContent(multipart);
			mimeMessage.setSentDate(new Date());

			sender.send(mimeMessage);
		}catch(Exception ex){
			log.error("发送邮件出现错误 ...",ex);            
		}
	}

	/**
	 * 发简单邮件
	 * @param subject 邮件主题
	 * @param content 邮件内容
	 * @param from 发件人邮箱
	 * @param to 收件人邮箱(多收件人邮箱以;号分隔)
	 */
	public static void sendMail(String subject,String content,String from,String to){
		sendMail(subject, content,null, from, to);
	}

}